import {
  Catch,
  ExceptionFilter,
  HttpException,
  ArgumentsHost,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';
import { QueryFailedError } from 'typeorm';

@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest();

    let message = '网络服务器错误',
      code = HttpStatus.INTERNAL_SERVER_ERROR;

    if (exception instanceof HttpException) {
      // nestjs内置的错误
      const o: string | any = exception.getResponse();
      message = o?.message || o || '未知错误';
      code = exception.getStatus();
    } else if (exception instanceof QueryFailedError) {
      // 数据库查询失败异常
      message = exception.message || '数据库操作失败';
      code = HttpStatus.INTERNAL_SERVER_ERROR;
    } else if (exception instanceof Error) {
      // new Error()
      message = exception.message;
    } else if (
      Object.prototype.toString.call(exception) === '[object Object]'
    ) {
      // 自定义的错误
      code = HttpStatus.BAD_REQUEST;
      message = exception?.message || message;
    }

    if ('ECONNABORTED' === exception?.code) {
      message = '连接被终止';
    } else if ('ETIMEDOUT' === exception?.code) {
      message = '连接超时';
    } else if ('ENETUNREACH' === exception?.code) {
      message = '网络不可达';
    } else if ('ERR_BAD_RESPONSE' === exception?.code) {
      message = `目标服务器异常`;
    }

    response.status(200).json({
      code,
      message,
      data: null,
    });
  }
}
